package com.fablesoft.projectdatacollect.ui;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.fablesoft.projectdatacollect.MyApplication;
import com.fablesoft.projectdatacollect.R;
import com.fablesoft.projectdatacollect.album.ShowAllPhotoActivity;
import com.fablesoft.projectdatacollect.bean.BaseResponse;
import com.fablesoft.projectdatacollect.bean.Campaign;
import com.fablesoft.projectdatacollect.bean.CampaignBean;
import com.fablesoft.projectdatacollect.bean.CampaignListResponse;
import com.fablesoft.projectdatacollect.bean.CampaignResponse;
import com.fablesoft.projectdatacollect.bean.FileBean;
import com.fablesoft.projectdatacollect.bean.MemberListResponse;
import com.fablesoft.projectdatacollect.http.HttpListener;
import com.fablesoft.projectdatacollect.http.HttpThread;
import com.fablesoft.projectdatacollect.util.Config;
import com.fablesoft.projectdatacollect.util.Log4jUtil;
import com.nostra13.universalimageloader.core.ImageLoader;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class SafeCampaignDetailActivity extends BaseRequestActivity {

    private static final String TAG = "SafeCampaignDetailActivity";
    private TextView tv1, tv2, tv3, tv4;
    private TextView organizeDepartment;
    private TextView meetingTime;
    private TextView meetingPlace;
    private TextView supportPeople;
    private TextView signCount;
    private TextView photoCount;
    private TextView title;
    private String id;
    private String type;
    private CampaignBean campaign;
    private static final int INFO_REQUEST_CODE = 101;
    private static final int SUBMIT_REQUEST_CODE = 102;
    private static final int PHOTO_UPDATE_LIST_CODE = 201;
    private static final int SIGN_IN_UPDATE_LIST_CODE = 202;
    private boolean isSubmit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_safe_campaign_detail);
        id = getIntent().getStringExtra("activityId");
        type = getIntent().getStringExtra("type");
        isSubmit = getIntent().getBooleanExtra("isSubmit", false);
        initView();
        sendGetRequest(Config.CAMPAIGN_DETAIL_URL + "?id=" + id, CampaignResponse.class);
        createLoadingDialog(this);
        showDialog("加载中");
    }

    private OnClickListener mOnClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.back:
                    finish();
                    break;
                case R.id.submit_btn:
                    if (isSubmit){
                        Toast.makeText(SafeCampaignDetailActivity.this, "已归档", Toast.LENGTH_SHORT).show();
                        finish();
                        return;
                    }
                    if (campaign == null) {
                        Toast.makeText(SafeCampaignDetailActivity.this, "安全活动获取失败，无法归档！", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    int sum = 0;
                    if (!TextUtils.isEmpty(signCount.getText())) {
                        sum = Integer.valueOf(signCount.getText().toString());
                    }
                    if (sum == 0) {
                        Toast.makeText(SafeCampaignDetailActivity.this, "安全活动无人签到，无法归档！", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    int count = 0;
                    if (!TextUtils.isEmpty(signCount.getText())) {
                        try {
                            count = Integer.valueOf(signCount.getText().toString());
                        } catch (Exception e) {
                            Log4jUtil.e(e.toString());
                        }
                    }
                    if (count <= 0) {
                        Toast.makeText(SafeCampaignDetailActivity.this, "安全活动未添加照片，无法归档！", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    sendRequest(Config.SUBMIT_CAMPAIGN_URL + id, null, BaseResponse.class);
                    createLoadingDialog(SafeCampaignDetailActivity.this);
                    showDialog("提交中");
                    break;
                case R.id.photo_btn:
                    Intent i = new Intent(SafeCampaignDetailActivity.this, PhotoActivity.class);
                    i.putExtra("id", id);
                    if (campaign != null && campaign.getImageFiles() != null) {
                        i.putExtra("files", campaign.getImageFiles());
                    }
                    startActivityForResult(i, 0);
                    break;
                case R.id.sign_in_btn:
                    Intent intent = new Intent(SafeCampaignDetailActivity.this, SignInActivity.class);
                    intent.putExtra("id", id);
                    startActivityForResult(intent, 0);
                    break;
            }
        }
    };

    protected void initView() {
        tv1 = (TextView) findViewById(R.id.tv_1);
        tv2 = (TextView) findViewById(R.id.tv_2);
        tv3 = (TextView) findViewById(R.id.tv_3);
        tv4 = (TextView) findViewById(R.id.tv_4);
        if (!TextUtils.isEmpty(type) && type.equals("1")) {
            tv1.setText(getResources().getString(R.string.tech_type));
            tv2.setText(getResources().getString(R.string.tech_time));
            tv3.setText(getResources().getString(R.string.tech_address));
            tv4.setText(getResources().getString(R.string.tech_person));
        } else if (!TextUtils.isEmpty(type) && type.equals("2")) {
            tv1.setText(getResources().getString(R.string.organize_department));
            tv2.setText(getResources().getString(R.string.teach_time));
            tv3.setText(getResources().getString(R.string.teach_address));
            tv4.setText(getResources().getString(R.string.teach_person));
        }
        organizeDepartment = (TextView) findViewById(R.id.organize_department);
        meetingTime = (TextView) findViewById(R.id.meeting_time);
        meetingPlace = (TextView) findViewById(R.id.meeting_place);
        supportPeople = (TextView) findViewById(R.id.support_people);
        signCount = (TextView) findViewById(R.id.sign_count);
        photoCount = (TextView) findViewById(R.id.photo_count);
        title = (TextView) findViewById(R.id.tv_title);
        View submitBtn = findViewById(R.id.submit_btn);
        View photoBtn = findViewById(R.id.photo_btn);
        View signInBtn = findViewById(R.id.sign_in_btn);
        View back = findViewById(R.id.back);
        submitBtn.setOnClickListener(mOnClickListener);
        photoBtn.setOnClickListener(mOnClickListener);
        signInBtn.setOnClickListener(mOnClickListener);
        back.setOnClickListener(mOnClickListener);
    }

    private void initData() {
        title.setText(campaign.getName());
        if (!TextUtils.isEmpty(type)&&type.equals("1")) {
            if (campaign.getTechnicalType().equals("1")) {
                organizeDepartment.setText("项目部级");
            } else if (campaign.getTechnicalType().equals("2")) {
                organizeDepartment.setText("班组级");
            } else if (campaign.getTechnicalType().equals("3")) {
                organizeDepartment.setText("工种级");
            }
        } else {
            organizeDepartment.setText(campaign.getOrganizer());
        }
        meetingTime.setText(new SimpleDateFormat("yyyy年MM月dd日").format(campaign.getStartTime()));
        meetingPlace.setText(campaign.getSite());
        supportPeople.setText(campaign.getSpeaker());
        signCount.setText(TextUtils.isEmpty(campaign.getSum()) ? "0" : campaign.getSum());
        photoCount.setText(campaign.getImageFiles() == null ? "0" : campaign.getImageFiles().size() + "");
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            dismissDialog();
            switch (msg.what) {
                case INFO_REQUEST_CODE:
                    CampaignResponse result = (CampaignResponse) msg.obj;
                    if (result == null) {
                        Toast.makeText(SafeCampaignDetailActivity.this, R.string.request_error,
                                Toast.LENGTH_SHORT).show();
                    } else {
                        if (result.getSuccess()) {
                            campaign = result.getData();
                            initData();
                        }
                    }
                    break;

                case SUBMIT_REQUEST_CODE:
                    BaseResponse baseResponse = (BaseResponse) msg.obj;
                    if (baseResponse == null) {
                        Toast.makeText(SafeCampaignDetailActivity.this, R.string.request_error,
                                Toast.LENGTH_SHORT).show();
                    } else {
                        if (baseResponse.getSuccess()) {
                            if (PhotoActivity.imageList != null) {
                                PhotoActivity.imageList.clear();
                                PhotoActivity.imageList = null;
                            }
                            Toast.makeText(SafeCampaignDetailActivity.this, "归档成功！",
                                    Toast.LENGTH_SHORT).show();
                            setResult(SafeCampaignNewActivity.UPDATE_LIST_CODE);
                            finish();
                        } else {
                            Toast.makeText(SafeCampaignDetailActivity.this, "归档失败！",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                    break;
            }
        }

        ;
    };

    @Override
    protected void onDestroy() {
        if (PhotoActivity.imageList != null) {
            PhotoActivity.imageList.clear();
            PhotoActivity.imageList = null;
        }
        super.onDestroy();
    }

    @Override
    public void onRequestFinish(BaseResponse response) {
        Message msg = mHandler.obtainMessage();
        msg.obj = response;
        if (response instanceof CampaignResponse) {
            msg.what = INFO_REQUEST_CODE;
        } else {
            msg.what = SUBMIT_REQUEST_CODE;
        }
        mHandler.sendMessage(msg);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == PHOTO_UPDATE_LIST_CODE) {
            sendGetRequest(Config.CAMPAIGN_DETAIL_URL + "?id=" + id, CampaignResponse.class);
            showDialog("刷新中");
            if (PhotoActivity.imageList != null && PhotoActivity.imageList.size() > 0) {
                photoCount.setText((PhotoActivity.imageList.size() - 1) + "");
            }
        } else if (resultCode == SIGN_IN_UPDATE_LIST_CODE) {
            signCount.setText(data.getCharSequenceExtra("count"));
        }
    }
}
